import { initState } from "./initState";
import { compileTpFunction } from './compile/index'
// import {mountComponent} from './vnode/index'
import { callHook, mountComponent } from './lifecycle'
import { mergeOptions } from "./utils/index";


export function initMixin (Vue) {
  Vue.prototype._init = function (options) {
    // console.log('options==', options)

    let vm = this;
    vm.$options = mergeOptions(Vue.options, options);
    // console.log('vm===', vm)

    callHook(vm, 'beforeCreate')

    // 初始化状态
    initState(vm);

    callHook(vm, 'created')

    
    // 渲染模版
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }

  }

  // 初始化 $mount
  Vue.prototype.$mount = function (el) {
    let vm = this;
    let options = vm.$options;
    el = document.querySelector(el)
    vm.$el = el;

    if (!options.render) {
      let template = options.template;

      if (!template && el) {
        //  获取el上面的html
        el = el.outerHTML;
        
        // 变成ast语法树
        let render = compileTpFunction(el)
        // console.log('render==', render)

        // 1、将render函数变成vnode
        // 2、vnode变成真是DOM
        options.render = render
      }
    }

    // 挂载组件
    mountComponent(vm, el)
  }

}

